﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Viettel.VOFFICE.DAO.DAL;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class NodeUserController : BaseController
    {
        /// <summary>
        /// Thêm một người dùng vào node của luồng
        /// </summary>
        /// <param name="nodeUser"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("add_node_user")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddNodeUser(NodeUserModel nodeUser)
        {
            try
            {
                List<ValidationResult> eResults;
                if (nodeUser.IsValid(out eResults))
                {
                    var nuDb = new NodeUser()
                    {
                        UserId = nodeUser.UserId,
                        NodeId = nodeUser.NodeId,
                        FlowId = nodeUser.FlowId,
                        MainExecutor = nodeUser.MainExecutor,
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                        IsActive = nodeUser.IsActive,
                    };
                    unitOfWork.NodeUserRepository.Insert(nuDb);
                    return Json(SimplyResponse.Response200());
                }
                else
                {
                    return Json(new JsonResponse() { Status = false, Result = string.Join(",</br>", eResults.Select(o => o.ErrorMessage)) });
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                throw;
            }
        }

        /// <summary>
        /// Thay đổi thông tin của 1 bản ghi node-user
        /// </summary>
        /// <param name="nodeUser"></param>
        /// <param name="modified"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("update_node_user")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateNodeUser(NodeUserModel nodeUser, string modified = "all")
        {
            try
            {
                return Json(new JsonResponse() { });
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                throw;
            }
        }

        /// <summary>
        /// Xóa người dùng trong node
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("delete_node_user")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteNodeUser(int nodeId, Guid userId)
        {
            try
            {
                unitOfWork.NodeUserRepository.Delete(nodeId, userId);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                throw;
            }
        }

        /// <summary>
        /// Biến người dùng trong node thành ngường xử lý chính.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="userId"></param>
        /// <param name="mainExcutor"> </param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("update_main_executor")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateMainExecutor(int nodeId, Guid userId, bool mainExcutor)
        {

            ITransaction tran = null;
            try
            {
                var unitofwork = new UnitOfWork();
                tran = unitofwork.BeginTransaction();
                if (mainExcutor == true)
                {
                    unitofwork.NodeUserRepository.RemoveAllMainExecutor(nodeId);
                }
                unitofwork.NodeUserRepository.UpdateExecutor(nodeId, userId, mainExcutor);
                tran.Commit();
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {
                if (tran != null) tran.Rollback();
                return Json(SimplyResponse.Response500());
                throw;
            }
            finally
            {
                if (tran != null)
                {
                    tran.Dispose();
                }
            }
        }
    }
}
